package cn.signalpha.modules.shop.service;

import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.tool.constant.SystemConstant;
import cn.signalpha.core.tool.node.ForestNodeMerger;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringPool;
import cn.signalpha.modules.shop.entity.GoodsCategory;
import cn.signalpha.modules.shop.mapper.GoodsCategoryMapper;
import cn.signalpha.modules.shop.vo.GoodsCategoryVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


/**
 * 商品分类 服务类
 *
 * @author suguangjun
 */
@Service
public class GoodsCategoryService extends ServiceImpl<GoodsCategoryMapper, GoodsCategory> {

	private final static String PARENT_ID = "parentId";
	private final static Integer CATEGORY_LEVEL = 1;

	/**
	 * 树形结构
	 */
	public List<GoodsCategoryVO> tree(Map<String, Object> params) {
		return ForestNodeMerger.merge(baseMapper.tree(params));
	}

	/**
	 * 懒加载列表
	 */
	public List<GoodsCategoryVO> lazyList(Long parentId, Map<String, Object> params) {
		if (Func.isEmpty(Func.toStr(params.get(PARENT_ID)))) {
			parentId = null;
		}
		return baseMapper.lazyList(parentId, params);
	}

	/**
	 * 保存或更新
	 */
	public boolean submit(GoodsCategory goodsCategory) {
		if(goodsCategory.getParentId() == null || goodsCategory.getParentId() == 0){
			goodsCategory.setPath(StringPool.ZERO);
			goodsCategory.setLevel(CATEGORY_LEVEL);
			goodsCategory.setParentId(SystemConstant.TOP_PARENT_ID);
		}else{
			GoodsCategory parent = baseMapper.selectById(goodsCategory.getParentId());
			goodsCategory.setLevel(parent.getLevel() + CATEGORY_LEVEL);
			goodsCategory.setPath(parent.getPath() + "," + parent.getId());
		}
		if(goodsCategory.getLevel() > 3){
			throw new ServiceException("最大支持三级分类");
		}
		return saveOrUpdate(goodsCategory);
	}

}
